import Taro from '@tarojs/taro'
import { getTopicList, searchTopic } from '../../services/topic'
import { parseTopic } from '../../utils/parse'

const namespace = 'topic_maidan'
export { namespace }
export default {
  namespace,
  state: {
    state: 0,
    hasMore: true,
    items: [],
    pageIndex: 1,
    pageSize: 15
  },
  effects: {
    *loadTopics(_, { select, call, put }) {
      let pageSize = yield select((state) => state[namespace].pageSize)
      let pageIndex = yield select((state) => state[namespace].pageIndex)
      const hasMore = yield select((state) => state[namespace].hasMore)
      const items = yield select((state) => state[namespace].items)
      if (!hasMore) {
        return
      } else {
        try {
          const res = yield call(getTopicList, pageIndex, pageSize)
          //   console.log(res.data.rows)
          if (res) {
            const arr = parseTopic(res.data.rows)
            console.log(arr)
            // const arr = res.data.rows.map((item) => {
            //   item.hasFollow = false
            //   item.iconPath = QI_NIU_YUN_URL + item.iconPath
            //   return item
            // })
            const hasmore = res.data.rows.length === pageSize
            const index = pageIndex + 1
            console.log(index)
            yield put({
              type: 'setState',
              payload: {
                items: [...items, ...arr],
                hasMore: hasmore,
                pageIndex: index,
                state: 3
              }
            })
          } else {
            yield put({
              type: 'setState',
              payload: {
                state: 2
              }
            })
          }
        } catch (error) {}
      }
    },
    *searchTopic(payload, { select, put, call }) {
      let pageSize = yield select((state) => state[namespace].pageSize)
      let pageIndex = yield select((state) => state[namespace].pageIndex)
      const { keyWord } = payload.payload
      // console.log(keyWord)
      try {
        const res = yield call(searchTopic, keyWord, pageIndex, pageSize)
        if (res) {
          const items = parseTopic(res.data.rows)
          console.log(items)
          // const items = res.data.rows.map((item) => {
          //   item.hasFollow = false
          //   item.iconPath = QI_NIU_YUN_URL + item.iconPath
          //   return item
          // })
          yield put({
            type: 'setState',
            payload: {
              items: items,
              hasMore: false
            }
          })
        }
      } catch (error) {}
    }
  },
  reducers: {
    setState(state, { payload }) {
      return { ...state, ...payload }
    }
  }
}
